<template>
  <div class="category-manager-container">
    <div class="category-header">
      <!-- <h2 class="category-title">
        <i class="fas fa-tags header-icon"></i>
        文章分类管理
      </h2> -->
      <h2 style="color: #3998a9;">文章分类管理</h2>
      <div class="action-buttons">
        <el-button type="primary" @click="showAddDialog" class="add-btn">
          <i class="fas fa-plus"></i> 添加分类
        </el-button>
        <el-button type="success" @click="refreshList" class="refresh-btn" :loading="loading">
          <i class="fas fa-sync-alt"></i> 刷新列表
        </el-button>
      </div>
    </div>

    <!-- 分类列表 -->
    <div class="category-list-container">
      <el-table :data="categories" style="width: 100%" v-loading="loading" row-key="id"
        :tree-props="{ children: 'children', hasChildren: 'hasChildren' }" empty-text="暂无数据">
        <el-table-column prop="articleCategoryName" label="分类名称" width="260">
          <template #default="{ row }">
            <div class="category-name-cell">
              <i class="fas fa-folder" style="color: #409EFF"></i>
              <span>{{ row.articleCategoryName }}</span>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="description" label="分类描述" />
        <el-table-column prop="articleCount" label="文章数量" width="100">
          <template #default="{ row }">
            <el-tag>{{ getTotalArticleCount(row) }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="sort" label="排序" width="80" />
        <el-table-column label="状态" width="100">
          <template #default="{ row }">
            <el-tag :type="row.isActive ? 'success' : 'danger'">
              {{ row.isActive ? '启用' : '已禁用' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="260" fixed="right">
          <template #default="{ row }">
            <div class="action-btns-container">
              <el-button size="small" @click.stop="showEditDialog(row)" class="action-btn edit-btn" plain>
                <i class="fas fa-edit"></i> 编辑
              </el-button>
              <el-button size="small" :type="row.isActive ? 'warning' : 'success'" plain
                @click.stop="toggleActiveHandler(row)">
                {{ row.isActive ? '禁用' : '启用' }}
              </el-button>
              <el-popconfirm title="确定要删除这个分类吗？" @confirm="deleteCategoryHandler(row)">
                <template #reference>
                  <el-button size="small" @click.stop class="action-btn delete-btn" plain
                    :disabled="row.children?.length > 0">
                    <i class="fas fa-trash-alt"></i> 删除
                  </el-button>
                </template>
              </el-popconfirm>
            </div>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!-- 添加/编辑分类对话框 -->
    <el-dialog :title="dialogTitle" v-model="dialogVisible" width="500px" :close-on-click-modal="false">
      <el-form ref="categoryFormRef" :model="categoryForm" :rules="categoryRules" label-width="100px">
        <el-form-item label="分类名称" prop="articleCategoryName">
          <el-input v-model="categoryForm.articleCategoryName" placeholder="请输入分类名称" />
        </el-form-item>
        <el-form-item label="父级分类" prop="parentId">
          <el-tree-select v-model="categoryForm.parentId" :data="categoryTree"
            :props="{ label: 'articleCategoryName', value: 'id' }" check-strictly clearable placeholder="不选即为顶级分类"
            style="width: 100%" />
        </el-form-item>
        <el-form-item label="分类描述" prop="description">
          <el-input v-model="categoryForm.description" type="textarea" :rows="3" placeholder="请输入分类描述" />
        </el-form-item>
        <el-form-item label="排序" prop="sort">
          <el-input-number v-model="categoryForm.sort" :min="0" :max="999" controls-position="right" />
        </el-form-item>
        <el-form-item label="状态" prop="isActive">
          <el-switch v-model="categoryForm.isActive" active-text="启用" inactive-text="禁用" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitCategoryForm" :loading="submitting">
          确认
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { useAuthStore } from '@/stores/authStore'
import {
  getArticleCategoryTree,
  addArticleCategory,
  updateArticleCategory,
  deleteArticleCategory,
  toggleArticleCategoryActive,
  checkCategoryNameUnique
} from '@/api/article'

const authStore = useAuthStore()

// -------------- 数据 --------------
const categories = ref([])
const categoryTree = ref([])
const loading = ref(false)
const submitting = ref(false)
const dialogVisible = ref(false)
const dialogTitle = ref('添加分类')
const categoryFormRef = ref()

const categoryForm = ref({
  id: '',
  articleCategoryName: '',
  parentId: null,
  description: '',
  sort: 0,
  isActive: true
})

// -------------- 校验规则 --------------
const validateNameUnique = async (rule, value, callback) => {
  if (!value) {
    callback()
    return
  }

  try {
    const response = await checkCategoryNameUnique({
      name: value,
      parentId: categoryForm.value.parentId,
      id: categoryForm.value.id || undefined
    })

    // 修正：检查API响应结构
    if (response.code === 200) {
      if (response.data) {
        callback() // 名称唯一
      } else {
        callback(new Error('该分类名称已存在'))
      }
    } else {
      callback(new Error(response.message || '验证名称唯一性失败'))
    }
  } catch (error) {
    callback(new Error('验证名称唯一性失败', error))
  }
}

const categoryRules = {
  articleCategoryName: [
    { required: true, message: '请输入分类名称', trigger: 'blur' },
    { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' },
    { validator: validateNameUnique, trigger: 'blur' }
  ],
  sort: [
    { required: true, message: '请输入排序值', trigger: 'blur', type: 'number' }
  ]
}

// -------------- 方法 --------------
// 计算分类的总文章数量（包括子分类）
const getTotalArticleCount = (category) => {
  let total = category.articleCount || 0

  // 递归计算子分类的文章数量
  const calculateChildrenCount = (children) => {
    if (!children || children.length === 0) return 0

    let childrenCount = 0
    for (const child of children) {
      childrenCount += (child.articleCount || 0)
      // 递归计算子分类的子分类
      if (child.children && child.children.length > 0) {
        childrenCount += calculateChildrenCount(child.children)
      }
    }
    return childrenCount
  }

  // 加上子分类的文章数量
  if (category.children && category.children.length > 0) {
    total += calculateChildrenCount(category.children)
  }

  return total
}

const loadCategories = async () => {
  loading.value = true
  try {
    const response = await getArticleCategoryTree()
    if (response.code === 200) {
      // 分类管理页面显示所有分类（包括禁用的）
      categories.value = response.data || []
      categoryTree.value = response.data || []
    } else {
      ElMessage.error(response.message || '获取分类列表失败')
    }
  } catch (error) {
    ElMessage.error('获取分类列表失败: ' + (error.message || '未知错误'))
  } finally {
    loading.value = false
  }
}

const showAddDialog = () => {
  dialogTitle.value = '添加分类'
  categoryForm.value = {
    id: '',
    articleCategoryName: '',
    parentId: null,
    description: '',
    sort: 0,
    isActive: true
  }
  dialogVisible.value = true
}

const showEditDialog = (row) => {
  dialogTitle.value = '编辑分类'
  categoryForm.value = {
    id: row.id,
    articleCategoryName: row.articleCategoryName,
    parentId: row.parentId || null,
    description: row.description || '',
    sort: row.sort ?? 0,
    isActive: row.isActive
  }
  dialogVisible.value = true
}

const submitCategoryForm = async () => {
  try {
    await categoryFormRef.value.validate()
    submitting.value = true

    const payload = {
      id: categoryForm.value.id || undefined,
      articleCategoryName: categoryForm.value.articleCategoryName,
      parentId: categoryForm.value.parentId,
      description: categoryForm.value.description,
      sort: categoryForm.value.sort,
      isActive: categoryForm.value.isActive,
      userId: authStore.user?.id // 确保传递用户ID
    }

    const api = payload.id ? updateArticleCategory : addArticleCategory
    const { code, message } = await api(payload)

    if (code === 200) {
      ElMessage.success(dialogTitle.value + '成功')
      dialogVisible.value = false
      loadCategories()
    } else {
      ElMessage.error(message || '操作失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('操作失败: ' + (error.message || '未知错误'))
    }
  } finally {
    submitting.value = false
  }
}

const toggleActiveHandler = async (row) => {
  try {
    const { code, message } = await toggleArticleCategoryActive(row.id)
    if (code === 200) {
      ElMessage.success('状态切换成功')
      loadCategories()
    } else {
      ElMessage.error(message || '状态切换失败')
    }
  } catch (error) {
    ElMessage.error('状态切换失败: ' + (error.message || '未知错误'))
  }
}

const deleteCategoryHandler = async (row) => {
  try {
    if (row.children?.length > 0) {
      ElMessage.error('不能删除含有子分类的父级分类')
      return
    }

    if (row.articleCount > 0) {
      await ElMessageBox.confirm(
        '该分类下存在文章，确认删除？',
        '警告',
        { type: 'warning' }
      )
    }

    const { code, message } = await deleteArticleCategory(row.id)
    if (code === 200) {
      ElMessage.success('删除成功')
      loadCategories()
    } else {
      ElMessage.error(message || '删除失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('删除失败: ' + (error.message || '未知错误'))
    }
  }
}

const refreshList = () => loadCategories()

// -------------- 初始化 --------------
onMounted(loadCategories)
</script>

<style scoped>
.category-manager-container {
  padding: 25px;
  background-color: #f8fafc;
  min-height: calc(100vh - 60px);
}

.category-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 25px;
  padding: 18px 25px;
  background-color: #fff;
  border-radius: 10px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.06);
}

.category-title {
  margin: 0;
  font-size: 22px;
  color: #2c3e50;
  display: flex;
  align-items: center;
  font-weight: 600;
}

.header-icon {
  margin-right: 12px;
  color: #409eff;
  font-size: 1.2em;
}

.action-buttons {
  display: flex;
  gap: 12px;
}

.add-btn,
.refresh-btn {
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 10px 18px;
  font-weight: 500;
  border-radius: 8px;
}

.category-list-container {
  background-color: #fff;
  border-radius: 10px;
  padding: 20px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.06);
}

.category-name-cell {
  display: flex;
  align-items: center;
  gap: 10px;
}

.category-name-cell i {
  font-size: 18px;
}

.action-btns-container {
  display: flex;
  gap: 8px;
}

.action-btn {
  display: flex;
  align-items: center;
  gap: 6px;
  padding: 7px 12px;
  border-radius: 6px;
  font-weight: 500;
}

.edit-btn {
  color: #409eff;
  border-color: #c6e2ff;
  background-color: #ecf5ff;
}

.delete-btn {
  color: #f56c6c;
  border-color: #fde2e2;
  background-color: #fef0f0;
}
</style>